﻿using System;
using System.IO;
using System.Windows.Forms;
using RSuite.Services;

namespace RSuite.R2.Services
{
    public class LocalService : LocalServiceBase
    {
        protected override object Process(string method, dynamic parameters, string taskId)
        {
            switch (method)
            {
                case "open":
                    return this.Open(parameters);
                case "save":
                    return this.Save(parameters["filename"], parameters["review"]);
                case "save-as":
                    return this.SaveAs(parameters["filename"], parameters["review"]);
                case "close":
                    base.Browser.FindForm().Close();
                    return null;
                default:
                    return null;
            }
        }

        private object Open(string filename)
        {
            var dialog = new OpenFileDialog();
            dialog.FileName = filename;
            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return string.Empty;
            }

            if (Path.GetExtension(dialog.FileName).ToLower() == ".rvw")
            {
                return new
                {
                    filename = dialog.FileName,
                    review = File.ReadAllText(dialog.FileName)
                };
            }
            else
            {
                return new
                {
                    filename = "",
                    review = base.ToJSON(new
                    {
                        codefile = Path.GetFileName(dialog.FileName),
                        code = File.ReadAllText(dialog.FileName),
                        reviewDate = DateTime.Today.ToString("yyyy/MM/dd HH:mm:ss")
                    })
                };
            }
        }

        private object Save(string filename, string data)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return this.SaveAs(filename, data);
            }
            else
            {
                File.WriteAllText(filename, data);
                return filename;
            }
        }

        private object SaveAs(string filename, string data)
        {
            var dialog = new SaveFileDialog();
            dialog.FileName = filename;
            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return string.Empty;
            }
            filename = dialog.FileName;

            File.WriteAllText(filename, data);

            return filename;
        }
    }
}